package gui.edit_objects;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.*;

import objects.Ville;

import bdd_handler.VilleDAO;
import bdd_handler.bdd;


public class Edit_Ville extends JFrame implements ActionListener{

	private static final long serialVersionUID = 1L;

	private JFrame parent;

	private VilleDAO vDAO;
	private Ville v;
	private JTextField ville_nom, ville_cp;
	private boolean mknew;
	private JButton valider, annuler;

	public Edit_Ville(JFrame parent, Ville ville){
		//recuperation de la fenetre parente
		this.parent=parent;
		this.parent.setVisible(false);

		//construction de la fenetre
		this.v=ville;
		if(v.getId_ville()==-1)
			mknew=true;
		else
			mknew=false;
		if(mknew)
			this.setTitle("Nouveau Ville");
		else
			this.setTitle("Editer Ville");
		this.setSize(500,200);
		this.setResizable(false);
		JPanel pan=new JPanel();
		pan.setLayout(null);
		this.setContentPane(pan);

		//creation des DAOs
		bdd db=new bdd();
		vDAO=new VilleDAO(db.getConnection());

		//creation objets internes
		ville_nom=new JTextField(v.getNom());
		ville_cp=new JTextField(v.getCp());
		valider=new JButton("valider");
		valider.addActionListener(this);
		annuler=new JButton("annuler");
		annuler.addActionListener(this);
		JLabel lbl_ville=new JLabel("Nom de la ville");
		JLabel lbl_n_dept=new JLabel("Code postal de la ville");

		//placer les objets
		pan.add(lbl_ville);
		lbl_ville.setBounds(10,10,200,20);
		pan.add(ville_nom);
		ville_nom.setBounds(220, 10, 200, 20);
		pan.add(lbl_n_dept);
		lbl_n_dept.setBounds(10, 40, 200, 20);
		pan.add(ville_cp);
		ville_cp.setBounds(220, 40, 200, 20);
		pan.add(annuler);
		annuler.setBounds(10, 70, 90, 20);
		pan.add(valider);
		valider.setBounds(110, 70, 90, 20);

		//action fermeture fenetre
		this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		this.addWindowListener(
				new WindowAdapter(){
					public void windowClosing(WindowEvent e){
						close();

					}
				}
				);
		//afficher la fenetre
		this.setVisible(true);
	}

	private void close(){
		this.parent.setVisible(true);
		this.dispose();
	}

	private void send()
	{
		v.setNom(ville_nom.getText());
		v.setCp(ville_cp.getText());
		if(mknew)
			vDAO.create(v);
		else
			vDAO.update(v);
	}

	private boolean check()
	{
		if(ville_nom.getText().equals(""))
		{
			JOptionPane.showMessageDialog(this.getContentPane(), "le nom de la ville n'a pas été renseigné", "Oh zut!", JOptionPane.ERROR_MESSAGE);
			return false;
		}
		return true;
	}
	@Override
	public void actionPerformed(ActionEvent e) {
		Object source=e.getSource();

		if(source==annuler)
		{
			close();
		}
		if(source==valider)
		{
			if(check())
			{
				send();
				close();
			}
		}

	}

}
